<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/6/20
 * Time: 20:01
 */

namespace App\Services;


class CommonHelper{

    /**将answer转换为数组
     * @param $answerStr
     * @return array
     */
    public static function convertAnswerToArr($answerStr){
        $answers = [];
        $answerArr = explode('##',$answerStr);
        if(count($answerArr)>0){
            foreach ($answerArr as $answer){
                $singleArr = explode(':',$answer);
                if(count($singleArr)>0){
                    $obj['index'] = $singleArr[0];
                    $obj['weight'] = self::formatWeight($singleArr[1]);
                    $obj['answer'] = $singleArr[2];
                    array_push($answers,$obj);
                }
            }
        }
        return $answers;
    }

    /**将answer转换为数组
     * @param $answerStr
     * @return array
     */
    public static function convertAnswerToObj($answerStr){
        $data = [];
        $answerArr = explode('##',$answerStr);
        if(count($answerArr)>0){
            foreach ($answerArr as $answer){
                $singleArr = explode(':',$answer);
                if(count($singleArr)>0){
                    $index = $singleArr[0];
                    $obj['index'] = $index;
                    $obj['weight'] = self::formatWeight($singleArr[1]);
                    $obj['answer'] = $singleArr[2];
                    $data[$index] = $obj;
                }
            }
        }
        return $data;
    }


    /**
     * 多选题格式化权重
     * @param $str 提交权重字符串
     * @return number
     */
    protected static function formatWeight($str){
        $arr = explode("|||",$str);
        $sum = array_sum($arr);
        return (string)$sum;
    }

}